package com.woniuxy.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.woniuxy.enums.TokenStatusEnum;

import java.util.Date;

/**
 * @Author: hlf
 * @Description: TODO
 * @Component: 成都蜗牛学苑
 **/
public class JWTUtils {
    public static final String SECRET_KEY = "myh123456"; //秘钥
    public static final long TOKEN_EXPIRE_TIME = 30 * 60 * 1000; //token过期时间
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 10 * 60 * 1000;
    //refreshToken过期时间
    private static final String ISSUER = "woniuxy"; //签发人
    /**     * 生成签名     */
    public static String generateToken(String uname){
        Date now = new Date();        //创建签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(now)  //签发时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) //过期时间，可由redis来控制
                .withClaim("uname", uname) //保存身份标识
                .sign(algorithm);
        return token;
    }
    /**     * 验证token     */
    public static TokenStatusEnum verify(String token){
        try {
            //签名算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();
            verifier.verify(token);
            return TokenStatusEnum.TOKEN_SUCCESS;
        } catch (TokenExpiredException ex){
            return TokenStatusEnum.TOKEN_EXPIRE;
            //ex.printStackTrace();
        } catch (Exception e) {
            return TokenStatusEnum.TOKEN_BAD;
        }
    }
    /**     * 从token获取uname     */
    public static String getUname(String token){
        try{
            return JWT.decode(token).getClaim("uname").asString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }
}